package org.jeecg.modules.phone.contractManagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.contract.entity.ContractManagement;
import org.jeecg.modules.contract.service.IContractManagementService;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * 手机端合同管理
 * Created by ：zou
 * Date：2019/9/13 11:52
 */
@Slf4j
@Api(tags="手机端-合同管理")
@RestController
@RequestMapping("/phone/contractManagement")
public class ContracttController {

    @Autowired
    private IContractManagementService contractManagementService;
    @Autowired
    private ISysRoleService sysRoleService;
    @Autowired
    private ISysUserService sysUserService;


    /**
     * 添加
     *
     * @param contractManagement
     * @return
     */
    @AutoLog(value="合同管理-添加")
    @ApiOperation(value="合同管理-添加", notes="合同管理-添加")
    @PostMapping(value="/add")
    public Result <org.jeecg.modules.contract.entity.ContractManagement> add(@RequestBody org.jeecg.modules.contract.entity.ContractManagement contractManagement) {
        Result <org.jeecg.modules.contract.entity.ContractManagement> result=new Result <org.jeecg.modules.contract.entity.ContractManagement>();
        try {

            SysUser user=new SysUser();
            // 设置创建时间
            user.setCreateTime(new Date());
            // 账号为手机号码
            user.setUsername(contractManagement.getContactPhone());
            // 身份证后4位为密码
            String tenantCard=contractManagement.getTenantCard() == null ? "123456" : contractManagement.getTenantCard();
            user.setPassword(tenantCard.substring(tenantCard.length() - 4, tenantCard.length()));
            String salt=oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode=PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag("0");
            // 获取员工roleId
            String roleId=this.getRoleId();
            //通过传入信息查询新的用户信息
            SysUser users=sysUserService.getOne(new QueryWrapper <SysUser>(user));
            if (users == null) {

                sysUserService.addUserWithRole(user, roleId);

            }


            // 小区 + 房屋 + 房间
            String contractName=contractManagement.getHousingEstate() == null ? "" : contractManagement.getHousingEstate() + contractManagement.getHouse() == null ? "" : contractManagement.getHouse() + contractManagement.getHouseRoom() == null ? "" : contractManagement.getHouseRoom();
            // 合同名称
            contractManagement.setContactName(contractName);
            contractManagement.setStatus(0);
            contractManagement.setUserId(user.getId());
            // 乙方签字。
            contractManagement.setBpmStatus("1");

            contractManagementService.save(contractManagement);
            result.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            result.error500("操作失败");
        }
        return result;
    }

    /**
     * 获取员工Id
     *
     * @return
     */
    private String getRoleId() {
        List <SysRole> list=this.sysRoleService.list();
        String roleId="";
        if (list != null) {
            for (SysRole role : list) {

                if ("租客".equals(role.getRoleName())) {
                    return role.getId();
                }
            }
        }
        return roleId;
    }

    /**
     * 导出work 文档
     */
    @AutoLog(value="手机-Work导出")
    @ApiOperation(value="手机-Work导出", notes="手机-Work导出")
    @RequestMapping("/exportWord/{id}")
    public ResponseEntity <byte[]> exportWork(@PathVariable("id") String id, HttpServletRequest req) throws IOException {

        org.jeecg.modules.contract.entity.ContractManagement byId=contractManagementService.getById(id);
        // 转换Word文件
        File file=null;
        HttpHeaders httpHeaders=new HttpHeaders();
        try {
            file=this.contractManagementService.transitionWord(byId, req);


            httpHeaders.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            httpHeaders.setContentDispositionFormData("attachment", URLEncoder.encode("合同模板.docx", "utf-8"));

        } catch (Exception e) {
            e.printStackTrace();
        }


        return new ResponseEntity <>(FileUtils.readFileToByteArray(file), httpHeaders, HttpStatus.CREATED);

    }

    /**
     * 分页列表查询
     *
     * @param contractManagement
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value="手机端-分页列表查询")
    @ApiOperation(value="手机端-合同管理-分页列表查询", notes="手机端合同管理-分页列表查询")
    @GetMapping(value="/list")
    public Result <IPage <org.jeecg.modules.contract.entity.ContractManagement>> queryPageList(org.jeecg.modules.contract.entity.ContractManagement contractManagement, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo, @RequestParam(name="pageSize", defaultValue="10") Integer pageSize, HttpServletRequest req) {
        Result <IPage <org.jeecg.modules.contract.entity.ContractManagement>> result=new Result <IPage <org.jeecg.modules.contract.entity.ContractManagement>>();
        QueryWrapper <org.jeecg.modules.contract.entity.ContractManagement> queryWrapper=QueryGenerator.initQueryWrapper(contractManagement, req.getParameterMap());
        Page <org.jeecg.modules.contract.entity.ContractManagement> page=new Page <org.jeecg.modules.contract.entity.ContractManagement>(pageNo, pageSize);
        IPage <org.jeecg.modules.contract.entity.ContractManagement> pageList=contractManagementService.page(page, queryWrapper);
        result.setSuccess(true);
        result.setResult(pageList);
        return result;
    }

    /**
     * 编辑
     *
     * @param contractManagement
     * @return
     */
    @AutoLog(value="手機合同管理-编辑")
    @ApiOperation(value="手機合同管理-编辑", notes="手機合同管理-编辑")
    @PostMapping(value="/contract/edit")
    public Result <ContractManagement> edit(@RequestBody ContractManagement contractManagement) {
        Result <ContractManagement> result=new Result <ContractManagement>();
        ContractManagement contractManagementEntity=contractManagementService.getById(contractManagement.getPkManagement());

        if (contractManagementEntity == null) {
            result.error500("未找到对应实体");
        } else {
            contractManagementEntity.setBpmStatus("2");
            contractManagementEntity.setSignDate(contractManagement.getSignDate());
            contractManagementEntity.setSignTenantry(contractManagement.getSignTenantry());
            boolean ok=contractManagementService.updateById(contractManagementEntity);
            //TODO 返回false说明什么？
            if (ok) {
                result.success("修改成功!");
            }
        }

        return result;
    }
}
